/*******************************************************************************
 * Copyright (c) 2010-2011 Robert Fraser                                       *
 *                                                                             *
 * Permission is hereby granted, free of charge, to any person obtaining a     *
 * copy of this software and associated documentation files (the "Software"),  *
 * to deal in the Software without restriction, including without limitation   *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,    *
 * and/or sell copies of the Software, and to permit persons to whom the       *
 * Software is furnished to do so, subject to the following conditions:        *
 *                                                                             *
 *   - The above copyright notice and this permission notice shall be included *
 *     in all copies or substantial portions of the Software.                  *
 *                                                                             *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,    *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER      *
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING     *
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER         *
 * DEALINGS IN THE SOFTWARE.                                                   *
 *******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using zeal.core;
using zeal.ui.util;
using zeal.util;

namespace zeal.ui.graph
{
    internal sealed partial class GraphEditor : DocumentEditor
    {
        public const double GRID_SIZE = 20;
        public const int Z_INDEX_EDGES = 0;
        public const int Z_INDEX_NODES = 1;
        public const int Z_INDEX_SELECTED_EDGES = 2;
        public const int Z_INDEX_SELECTED_NODES = 3;
        public const int Z_INDEX_TEMPORARY_EDGES = 4;
        
        private static readonly Log _log = LogManager.getLog(typeof(GraphEditor));
        private static ClipboardData _clipboard;
        private readonly GraphViewer _viewer;
        private readonly TextureGraph _graph;
        private MoveMemento _moveMemento;

        public GraphEditor()
        {
            _graph = new TextureGraph();
            _mode = _defaultMode = new DefaultEditorMode(this);
            Content = _viewer = new GraphViewer();

            initCommands();
            initEvents();
        }
        
        public bool isEnabled { get { return _viewer.IsEnabled; } set { _viewer.IsEnabled = value; } }
        public Cursor cursor { get { return _viewer.Cursor; } set { _viewer.Cursor = value; } }
        public IEnumerable<GraphNode> nodes { get { return surface.Children.OfType<GraphNode>(); } }
        public IEnumerable<GraphEdge> edges { get { return surface.Children.OfType<GraphEdge>(); } }
        public IEnumerable<GraphNode> selectedNodes { get { return nodes.Where(node => node.IsSelected); } }
        public static bool isSelectionModifierKeyDown { get { return (Keyboard.Modifiers & (ModifierKeys.Shift | ModifierKeys.Control)) != ModifierKeys.None; } }
        public static bool snapToGrid { get { return ApplicationSettings.Default.snapToGrid; } }
        public void selectAll() { foreach (GraphNode node in nodes) node.IsSelected = true; }
        public void deselectAll() { foreach (GraphNode node in nodes) node.IsSelected = false; }
        
        private TextureGraph graph { get { return _graph; } }
        private MeasuringCanvas surface { get { return _viewer.surface; } }
        private Panel overlay { get { return _viewer.overlay; } }

        public void beginConnect(GraphPort source, MouseButtonEventArgs args)
        {
            Debug.Assert(isInDefaultMode, "Must be in default state to begin a connection");
            _mode = new ConnectEditorMode(this, source, getSurfacePosition(args));
        }

        public static void snap(ref double x, ref double y) 
        { 
            x = Math.Round(x / GRID_SIZE) * GRID_SIZE; 
            y = Math.Round(y / GRID_SIZE) * GRID_SIZE;
        }

        public bool snapIfNeeded(ref double x, ref double y) { if (snapToGrid) snap(ref x, ref y); return false; }
        public bool snapIfNeeded(GraphNode node)
        {
            double x = node.left;
            double y = node.top;
            bool snapped = snapIfNeeded(ref x, ref y);
            if (snapped)
            {
                node.left = x;
                node.top = y;
            }
            return snapped;
        }

        public void onDragBegin()
        {
            Debug.Assert(_moveMemento == null);
            _moveMemento = new MoveMemento("Move");
            foreach (GraphNode item in selectedNodes)
                _moveMemento.old.Add(item, new Point(item.left, item.top));
        }

        public void onDragEnd()
        {
            Debug.Assert(_moveMemento != null);

            // If the user has snap to grid on, or otherwise move was triggered without anything
            // actually being moved, we don't want to create an undo memento
            bool somethingActuallyMoved = false;
            foreach (GraphNode item in selectedNodes)
            {
                Point cur = new Point(item.left, item.top);
                Point old;
                // ReSharper disable PossibleNullReferenceException
                if (!_moveMemento.old.TryGetValue(item, out old))
                // ReSharper restore PossibleNullReferenceException
                {
                    _log.warning("doEndMove() encountered node {0} which was not added during doBeginMove()", item.node);
                    old = cur;
                }
                _moveMemento.cur.Add(item, cur);
                somethingActuallyMoved |= old.X != cur.X;
                somethingActuallyMoved |= old.Y != cur.Y;
            }
            if (somethingActuallyMoved) pushUndo(_moveMemento);
            _moveMemento = null;
        }

        public void onDragDelta(double dx, double dy)
        {
            foreach (GraphNode item in selectedNodes)
            {
                double x = item.left + dx;
                double y = item.top + dy;
                snapIfNeeded(ref x, ref y);
                item.left = x;
                item.top = y;
            }
        }

        protected override bool saveDocument(Stream stream)
        {
            graph.write(stream);
            return true;
        }
    }
}